package com.zj.joke.db;

/**
 * Created by zhangjian on 13-12-6.
 */

import com.activeandroid.ActiveAndroid;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.From;
import com.activeandroid.query.Select;

import java.util.List;

@Table(name = "DBItem")
public class DBItem extends Model {
	@Column(name = "category")
	public String category;

	@Column(name = "read")
	public boolean read;

	@Column(name = "text")
	public String text;

	@Column(name = "title")
	public String title;

	@Column(name = "url")
	public String url;

	public static void add(DBStoreItem paramDBStoreItem) {
		DBItem localDBItem = new DBItem();
		localDBItem.category = paramDBStoreItem.category;
		localDBItem.title = paramDBStoreItem.title;
		localDBItem.text = paramDBStoreItem.text;
		localDBItem.read = false;
		localDBItem.url = paramDBStoreItem.url;
		localDBItem.save();
	}

	public static int getDBItemSize(String category) {
		return new Select().from(DBItem.class).where("category=?", category)
				.execute().size();
	}

	public static long getDBItemUnReadSize(String category) {
		From localFrom = new Select().from(DBItem.class);
		return localFrom.where("read = ? and category = ?", 0, category)
				.execute().size();
	}

	public static List<DBItem> getDBItemUnRead(String category) {
		return new Select().from(DBItem.class)
				.where("category = ? and  read= ?", category, 0).execute();
	}

	public static List<DBItem> getDBItems(String category) {
		return new Select().from(DBItem.class).where("category=?", category)
				.orderBy("id DESC").execute();
	}

	public static List<DBItem> getDBItems(String category, int start, int limit) {
		return new Select().from(DBItem.class).where("category=?", category)
				.offset(start).limit(limit).orderBy("id DESC").execute();
	}

	public static void shrinkTable() {
		ActiveAndroid.beginTransaction();
		try {
			List<DBItem> list = new Select().from(DBItem.class)
					.orderBy("id DESC").execute();
			if (list != null) {
				for (int i = 10000; i < list.size(); i++) {
					list.get(i).delete();
				}
			}
			ActiveAndroid.setTransactionSuccessful();
		} finally {
			ActiveAndroid.endTransaction();
		}
	}
}